package patrol.mobile.com.mobilepatrol.activity.toll;

import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.ui.ImagePreviewDelActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import patrol.mobile.com.mobilepatrol.R;
import patrol.mobile.com.mobilepatrol.activity.BaseActivity;
import patrol.mobile.com.mobilepatrol.activity.VideoPlayActivity;
import patrol.mobile.com.mobilepatrol.adapter.GlideImageLoader;
import patrol.mobile.com.mobilepatrol.adapter.ImagePickerAdapter;
import patrol.mobile.com.mobilepatrol.api.Urls;
import patrol.mobile.com.mobilepatrol.bean.TrafficChargeDickListBean;
import patrol.mobile.com.mobilepatrol.bean.UpImgInfoBean;
import patrol.mobile.com.mobilepatrol.picker.matisse.Matisse;
import patrol.mobile.com.mobilepatrol.picker.matisse.MimeType;
import patrol.mobile.com.mobilepatrol.picker.matisse.engine.GlideEngine;
import patrol.mobile.com.mobilepatrol.utils.CommonParamsHelper;
import patrol.mobile.com.mobilepatrol.utils.CommonUtil;
import patrol.mobile.com.mobilepatrol.utils.Constants;
import patrol.mobile.com.mobilepatrol.utils.FileUtil;
import patrol.mobile.com.mobilepatrol.utils.GsonUtil;
import patrol.mobile.com.mobilepatrol.utils.LuBanHelper;
import patrol.mobile.com.mobilepatrol.utils.StringUtils;
import patrol.mobile.com.mobilepatrol.utils.TimeUtils;
import patrol.mobile.com.mobilepatrol.utils.net.HttpCallBack;
import patrol.mobile.com.mobilepatrol.utils.net.HttpSender;
import patrol.mobile.com.mobilepatrol.widget.MySpinner;
import patrol.mobile.com.mobilepatrol.widget.dialog.SelectDialog;

import static patrol.mobile.com.mobilepatrol.activity.office.AdviceDetailActivity.IMAGE_ITEM_ADD;
import static patrol.mobile.com.mobilepatrol.utils.SPUtils.get;

public class TrafficChargeUpDataActivity extends BaseActivity implements ImagePickerAdapter.OnRecyclerViewItemClickListener {
    @BindView(R.id.tv_riqi)
    TextView tvRiqi;
    @BindView(R.id.tv_danwei)
    TextView tvDanwei;
    @BindView(R.id.tv_shangbaoren)
    TextView tvShangbaoren;
    @BindView(R.id.et_tongxingfeiyong)
    EditText etTongxingfeiyong;
    @BindView(R.id.tv_lvse_cheliang)
    EditText tvLvseCheliang;
    @BindView(R.id.tv_lvse_feiyong)
    EditText tvLvseFeiyong;
    @BindView(R.id.tv_rukou)
    EditText tvRukou;
    @BindView(R.id.tv_chukou)
    EditText tvChukou;
    @BindView(R.id.et_total)
    EditText etTotal;
    @BindView(R.id.mySpinner)
    MySpinner mySpinner;
    @BindView(R.id.tv_teshu_shuoming)
    EditText tvTeshuShuoming;
    @BindView(R.id.btn_sure)
    Button btnSure;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    private String teshuqingkuang;

    private ArrayList<ImageItem> selImageList;
    private ImagePickerAdapter adapter;
    private int limitSize = 4;
    private List<String> imgUUIDs = new ArrayList<>();
    ArrayList<ImageItem> images = null;
    public static final int REQUEST_CODE_SELECT = 100;
    public static final int REQUEST_CODE_VSELECT = 102;
    public static final int REQUEST_CODE_PREVIEW = 101;
    private String videoPath = "";
    private HashMap<String, String> idDateBmnameMap;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_traffic_charge_up_data;
    }

    @Override
    public void setListener() {
    }

    @Override
    public void initTitle() {
        super.initTitle();
        iv_back.setImageResource(R.mipmap.up_white);
        iv_back.setVisibility(View.VISIBLE);
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CommonUtil.exitActivityAndBackAnim(TrafficChargeUpDataActivity.this, true);
            }
        });
        tv_center_title.setVisibility(View.VISIBLE);
        tv_center_title.setText("交通量收费额上报");
    }

    @Override
    public void initData() {
        super.initData();
        initImagePicker();
        selImageList = new ArrayList<>();
        adapter = new ImagePickerAdapter(this, selImageList, limitSize);
        adapter.setOnItemClickListener(this);
        recyclerView.setLayoutManager(new GridLayoutManager(this, limitSize));
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(adapter);
        tvDanwei.setText(patrol.mobile.com.mobilepatrol.manager.UserManager.getUser(current_id).bmname);
        tvRiqi.setText(TimeUtils.timeString(System.currentTimeMillis()));
        tvShangbaoren.setText(patrol.mobile.com.mobilepatrol.manager.UserManager.getUser(current_id).ryname);
        getDickList();
    }

    private void upImg() {
        if (selImageList != null && selImageList.size() != 0) {
            List<File> list = new ArrayList<>();
            List<Map<String, String>> params = new ArrayList<>();
            List<Map<String, String>> picparams = new ArrayList<>();
            for (String imgUUID : imgUUIDs) {
                Map<String, String> map = new HashMap<>();
                map.put("id", imgUUID);
                map.put("type", "orgTrafficTollDetail");
                params.add(map);
            }
            for (int i = 0; i < selImageList.size(); i++) {
                File file;
                File videofile;
                if (selImageList.get(i).mimeType.equals("image")) {
                    file = new File(selImageList.get(i).path);
                    list.add(file);
                    picparams.add(params.get(i));
                } else {
                    videofile = new File(selImageList.get(i).name);
                    HttpSender sender = new HttpSender(this, baseUrl, Urls.IMG_UP_LOAD);
                    Map<String, String> map = new HashMap<>();
                    map.put("id", imgUUIDs.get(i));
                    map.put("type", "orgTrafficTollDetail");
                    int finalI = i;
                    sender.upImgs2(videofile, map, new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                        }

                        @Override
                        public void onResponse(String response, int id) {
                            Toast.makeText(TrafficChargeUpDataActivity.this, "提交成功", Toast.LENGTH_SHORT).show();
                            if (finalI == selImageList.size() - 1) {
                                finish();
                            }
                        }
                    });
                }
            }

            LuBanHelper luBanHelper = new LuBanHelper(TrafficChargeUpDataActivity.this, list, picparams);
            luBanHelper.compression(new StringCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                }

                @Override
                public void onResponse(String response, int id) {
                    Toast.makeText(TrafficChargeUpDataActivity.this, "提交成功", Toast.LENGTH_SHORT).show();
                    finish();
                }
            });
        }
    }

    private void getDickList() {
        HttpSender sender = new HttpSender(this, baseUrl, Urls.DICT_LIST);
        sender.requestPost("dictType", "orgTrafficTollDetail_cases", new HttpCallBack(sender) {
            @Override
            public void onError(String code, Call call, Exception e) {

            }

            @Override
            public void onResponse(String code, String response) {
                JsonParser jp = new JsonParser();
                JsonObject jo = jp.parse(response).getAsJsonObject();

                JsonArray listArray = jo.getAsJsonArray("list");

                final List<TrafficChargeDickListBean> trafficChargeDickListBeans = GsonUtil.jsonToList(listArray.toString(), TrafficChargeDickListBean.class);
                List<String> list = new ArrayList<>();
                for (TrafficChargeDickListBean trafficChargeDickListBean : trafficChargeDickListBeans) {
                    list.add(trafficChargeDickListBean.getLabel());
                }
                teshuqingkuang = trafficChargeDickListBeans.get(0).getLabel();
                mySpinner.setmDatas(list, new MySpinner.CallBack() {
                    @Override
                    public void onSelect(int position) {
                        teshuqingkuang = trafficChargeDickListBeans.get(position).getLabel();
                    }
                });
            }
        });
    }

    private void submit() {
        String trim = etTongxingfeiyong.getText().toString().trim();
        String trim1 = tvLvseCheliang.getText().toString().trim();
        String trim2 = tvLvseFeiyong.getText().toString().trim();
        String trim3 = tvRukou.getText().toString().trim();
        String trim4 = tvChukou.getText().toString().trim();
        String trim5 = etTotal.getText().toString().trim();
        String trim6 = tvTeshuShuoming.getText().toString().trim();
        if (StringUtils.isEmpty(trim) || StringUtils.isEmpty(trim1) || StringUtils.isEmpty(trim2) || StringUtils.isEmpty(trim3) || StringUtils.isEmpty(trim4) || StringUtils.isEmpty(trim5) || StringUtils.isEmpty(trim6)) {
            showToast("请输入相关信息");
            return;
        }

        HashMap<String, String> stringStringHashMap = new HashMap<>();
        idDateBmnameMap = CommonParamsHelper.getIdDateBmnameMap();
        stringStringHashMap.put("mainJson", new Gson().toJson(greadData()));
        List<ImageItem> images = adapter.getImages();
        List<UpImgInfoBean> upImgInfoBeanList = new ArrayList<>();
        for (ImageItem image : images) {
            UpImgInfoBean imgInfoBean = new UpImgInfoBean();
            imgInfoBean.setBusniessId(idDateBmnameMap.get("id"));
            imgInfoBean.setContentType("jiankkElefailrpt");
            imgInfoBean.setFileType("img");
            String uuid = UUID.randomUUID().toString();
            imgUUIDs.add(uuid);
            imgInfoBean.setId(uuid);
            upImgInfoBeanList.add(imgInfoBean);
        }
        stringStringHashMap.put("sysAttachmentsJson", GsonUtil.bean2Json(upImgInfoBeanList));
        String json = new Gson().toJson(stringStringHashMap);
        Log.i("submit", "submit: " + json);
        HttpSender sender = new HttpSender(this, baseUrl, Urls.TRAFFIC_DETAIL_UP_LOAD);
        sender.requestPost(stringStringHashMap, new HttpCallBack(sender) {
            @Override
            public void onError(String code, Call call, Exception e) {

            }

            @Override
            public void onResponse(String code, String response) {
                Log.i("submit", "onResponse: " + response);
                showToast("上传成功");
                upImg();
            }
        });
    }

    private HashMap<String, Object> greadData() {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("orgId", patrol.mobile.com.mobilepatrol.manager.UserManager.getOrgNo());
        hashMap.put("account", patrol.mobile.com.mobilepatrol.manager.UserManager.getUserId());
        hashMap.put("id", patrol.mobile.com.mobilepatrol.manager.UserManager.getUserId() + System.currentTimeMillis());
        HashMap<String, String> hashMap1 = new HashMap<>();
        hashMap1.put("id", patrol.mobile.com.mobilepatrol.manager.UserManager.getOrgNo());
        hashMap1.put("orgName", patrol.mobile.com.mobilepatrol.manager.UserManager.getUser((String) get(Constants.current_id, "")).bmname);
        hashMap.put("org", hashMap1);
        String trim = etTongxingfeiyong.getText().toString().trim();
        String trim1 = tvLvseCheliang.getText().toString().trim();
        String trim2 = tvLvseFeiyong.getText().toString().trim();
        String trim3 = tvRukou.getText().toString().trim();
        String trim4 = tvChukou.getText().toString().trim();
        String trim5 = etTotal.getText().toString().trim();
        String trim6 = tvTeshuShuoming.getText().toString().trim();
        hashMap.put("upDate", TimeUtils.timeString(System.currentTimeMillis()));
        hashMap.put("upUserId", patrol.mobile.com.mobilepatrol.manager.UserManager.getOrgNo());
        hashMap.put("upUserName", patrol.mobile.com.mobilepatrol.manager.UserManager.getUserName());
        hashMap.put("toll", trim);
        hashMap.put("greenDerateCat", trim1);
        hashMap.put("greenDerateToll", trim2);
        hashMap.put("entrance", trim3);
        hashMap.put("exitus", trim4);
        hashMap.put("total", trim5);
        hashMap.put("cases", teshuqingkuang);
        hashMap.put("describes", trim6);
        hashMap.putAll(idDateBmnameMap);
        return hashMap;
    }

    @OnClick(R.id.btn_sure)
    public void onViewClicked() {
        submit();
    }

    private void initImagePicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);                      //显示拍照按钮
        imagePicker.setCrop(true);                            //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true);                   //是否按矩形区域保存
        imagePicker.setSelectLimit(4);              //选中数量限制
        imagePicker.setMultiMode(false);                      //多选
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);                       //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);                      //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);                         //保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);                         //保存文件的高度。单位像素
    }

    @Override
    public void onItemClick(View view, int position) {
        switch (position) {
            case IMAGE_ITEM_ADD:
                List<String> names = new ArrayList<>();
                names.add("拍照");
                names.add("相册");
                names.add("视频");
                showDialog(new SelectDialog.SelectDialogListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        switch (position) {
                            case 0: // 直接调起相机
                                /**
                                 * 0.4.7 目前直接调起相机不支持裁剪，如果开启裁剪后不会返回图片，请注意，后续版本会解决
                                 *
                                 * 但是当前直接依赖的版本已经解决，考虑到版本改动很少，所以这次没有上传到远程仓库
                                 *
                                 * 如果实在有所需要，请直接下载源码引用。
                                 */
                                //打开选择,本次允许选择的数量
                                ImagePicker.getInstance().setSelectLimit(limitSize - selImageList.size());
                                Intent intent = new Intent(TrafficChargeUpDataActivity.this, ImageGridActivity.class);
                                intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机
                                startActivityForResult(intent, REQUEST_CODE_SELECT);
                                break;
                            case 1:
                                //打开选择,本次允许选择的数量
                                ImagePicker.getInstance().setSelectLimit(limitSize - selImageList.size());
                                Intent intent1 = new Intent(TrafficChargeUpDataActivity.this, ImageGridActivity.class);
                                /* 如果需要进入选择的时候显示已经选中的图片，
                                 * 详情请查看ImagePickerActivity
                                 * */
//                                intent1.putExtra(ImageGridActivity.EXTRAS_IMAGES,images);
                                startActivityForResult(intent1, REQUEST_CODE_SELECT);
                                break;
                            case 2:
//                                Intent i = new Intent();
//                                i.setType("video/*"); //选择视频 （mp4 3gp 是android支持的视频格式）
//                                i.setAction(Intent.ACTION_GET_CONTENT);
//                                startActivityForResult(i, REQUEST_CODE_VSELECT);
                                Matisse.from(TrafficChargeUpDataActivity.this)
                                        .choose(MimeType.ofVideo())
                                        .showSingleMediaType(true)
                                        .theme(R.style.Matisse_Dracula)
                                        .countable(false)
                                        .maxSelectable(1)
                                        .imageEngine(new GlideEngine())
                                        .forResult(REQUEST_CODE_VSELECT);
                                break;
                            default:
                                break;
                        }

                    }
                }, names);
                break;
            default:
                if (adapter.getImages().get(position).mimeType.equals("image")) {
                    //打开预览
                    Intent intentPreview = new Intent(this, ImagePreviewDelActivity.class);
                    intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, (ArrayList<ImageItem>) adapter.getImages());
                    intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
                    intentPreview.putExtra(ImagePicker.EXTRA_FROM_ITEMS, true);
                    startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
                } else {
                    Intent intentPreview = new Intent(this, VideoPlayActivity.class);
                    intentPreview.putExtra("videopath", adapter.getImages().get(position).name);
                    startActivity(intentPreview);
                }

                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            switch (resultCode) {
                case ImagePicker.RESULT_CODE_ITEMS:
                    //添加图片返回
                    if (requestCode == REQUEST_CODE_SELECT) {
                        images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                        if (images != null) {
                            for (int i = 0; i < images.size(); i++) {
                                images.get(i).mimeType = "image";
                            }
                            selImageList.addAll(images);
                            adapter.setImages(selImageList);
                        }
                    }
                    break;
                case ImagePicker.RESULT_CODE_BACK:
                    //预览图片返回
                    if (requestCode == REQUEST_CODE_PREVIEW) {
                        images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS);
                        if (images != null) {
                            selImageList.clear();
                            selImageList.addAll(images);
                            adapter.setImages(selImageList);
                        }
                    }
                    break;
                case RESULT_OK:
                    //选择视频返回
                    if (requestCode == REQUEST_CODE_VSELECT) {
                        List<String> videoUrls = Matisse.obtainPathResult(data);
                        Log.e("videoUrls", videoUrls.get(0));
                        videoPath = videoUrls.get(0);
                        MediaMetadataRetriever retr = new MediaMetadataRetriever();
                        retr.setDataSource(videoPath);
                        //获取第一帧图像的bitmap对象
                        Bitmap bitmap = retr.getFrameAtTime();
                        String imgUrl = FileUtil.saveImg2Gallery(this, bitmap,
                                System.currentTimeMillis() / 1000 + "");
                        ImageItem imageItem = new ImageItem();
                        imageItem.path = imgUrl;
                        imageItem.name = videoPath;
                        imageItem.mimeType = "video";
                        selImageList.add(imageItem);
                        adapter.setImages(selImageList);

                    }
                    break;
            }
        }
    }

    private SelectDialog showDialog(SelectDialog.SelectDialogListener listener, List<String> names) {
        SelectDialog dialog = new SelectDialog(this, R.style
                .transparentFrameWindowStyle,
                listener, names);
        if (!this.isFinishing()) {
            dialog.show();
        }
        return dialog;
    }
}
